package com.huluobo.jetpackkotlindemo.room

import android.os.Bundle
import android.util.Log
import androidx.room.Room
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.huluobo.jetpackkotlindemo.MyApplication
import com.huluobo.jetpackkotlindemo.databinding.ActivityRoomBinding
import com.huluobo.jetpackkotlindemo.viewbinding.BaseActivity

/**
 * Created by lc on 2022/12/12.
 */
class RoomActivity : BaseActivity<ActivityRoomBinding>() {
    override fun getViewBinding(): ActivityRoomBinding = ActivityRoomBinding.inflate(layoutInflater)

//    //直接在主线程中创建数据库,这种形式消耗的资源比较大
//    var accountDb = Room.databaseBuilder(this, AccountDataBase::class.java, "account.db").build()

    //通过伴生函数创建一个Room的单例,并且懒加载使用同步处理
    //allowMainThreadQueries()可以强制数据库查询运行在主线程当中,但是可能会影响UI线程造成卡顿
    //fallbackToDestructiveMigration() 破坏性的重建数据库,会丢失所有旧数据
    companion object {
        val accountDb by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            Room.databaseBuilder(
                MyApplication.instance.applicationContext,
                AccountDataBase::class.java,
                "account.db"
            ).allowMainThreadQueries()
//                .addMigrations(MIGRATION_1_2,MIGRATION_2_3)//一起添加2个数据库升级策略
                .addMigrations(MIGRATION_1_2)
                .build()
        }

        private val MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE Account ADD COLUMN _loginIpAddress TEXT NOT NULL DEFAULT ''")
            }
        }

//        private val MIGRATION_2_3 = object : Migration(2, 3) {
//            override fun migrate(database: SupportSQLiteDatabase) {
//                database.execSQL("ALTER TABLE Account ADD COLUMN _loginIpAddress TEXT NOT NULL DEFAULT ''")
//            }
//        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewBinding.btnSave.setOnClickListener {
            val account = accountDb.accountDao.findAccountByLoginAccount(getLoginAccount())

            //let 表示判断当前的对象是否为空,如果不为空则走第一个大括号,如果为空,则走?:的大括号
            account?.let {
                Log.i("TagA", "账号:${getLoginAccount()},账号已经存在")
                //账号如果存在,密码如果相同,不做任何操作
                if (it.loginPassword != getLoginPassword()) {
                    //如果账号密码不同,则做出更新的操作
                    it.loginPassword = getLoginPassword()
                    accountDb.accountDao.updateAccountBean(it)
                }
            } ?: let {
                //如果账号不存在,则保存
                val accountBean = AccountBean(
                    null,
                    loginAccount = getLoginAccount(),
                    loginPassword = getLoginPassword(),
                    loginIpAddress = getLoginIpAddress()
                )
                accountDb.accountDao.insertAccount(accountBean)
            }

        }

        mViewBinding.btnQuery.setOnClickListener {
            val list = accountDb.accountDao.loadAccountList()
            list?.let {
                mViewBinding.tvResult.text = ""
                for (i in it.indices) {
                    mViewBinding.tvResult.append("账号:${it[i].loginAccount}")
                    mViewBinding.tvResult.append(",密码:${it[i].loginPassword}")
                    mViewBinding.tvResult.append(",Ip地址:${it[i].loginIpAddress}")
                }
            }
        }

        mViewBinding.btnDelete.setOnClickListener {
            val list = accountDb.accountDao.loadAccountList()
            list?.let {
                for (i in it.indices) {
                    if (it[i].loginAccount == getLoginAccount()) {
                        accountDb.accountDao.deleteAccount(it[i])
                    }
                }
            }
        }
    }

    private fun getLoginPassword(): String {
        return mViewBinding.edLoginPassword.text.trim().toString()
    }

    private fun getLoginAccount(): String {
        return mViewBinding.edLoginAccount.text.trim().toString()
    }

    private fun getLoginIpAddress(): String {
        return mViewBinding.edLoginIpAddress.text.trim().toString()
    }

    override fun onDestroy() {
        super.onDestroy()
        closeDb()
    }

    fun closeDb() {
        if (accountDb.isOpen) {
            accountDb.close()
        }
    }
}